package com.haixinga.commbiz.commons.utils;

import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;

public class FileKit {

	public static boolean moveFile(String sourceFilePath, String newFilePath){
		File newFile = new File(newFilePath);
		newFile.getParentFile().mkdirs();
		return new File(sourceFilePath).renameTo(newFile);

	}

	public static boolean copyFile(String sourceFilePath, String newFilePath){

		try {
			File newFile = new File(newFilePath);
			newFile.getParentFile().mkdirs(); //先创建文件夹，避免复制失败

			FileCopyUtils.copy(new File(sourceFilePath), new File(newFilePath));
		} catch (IOException e) {
			return false;
		}

		return true;
	}


	public static File createFile(String filePath){
		try {

			File file = new File(filePath);
			if(!file.exists())
					file.mkdirs();
					file.createNewFile();

			return file;

		}catch(IOException e) {
			return null;
		}
	}


	public static void createDir(String filePath){

			File file = new File(filePath);
			if(!file.exists())
				file.getParentFile().mkdirs();
	}


	 public static void delFile(String fileFullPath){
         File file = new File(fileFullPath);
         if( file.exists() && file.isFile() )
             file.delete();
     }

     //删除文件夹 和文件夹下所有的内容
     public static boolean delDir(File dirFile){
		if(!dirFile.exists()){ //不存在
			return true;
		}

		if(dirFile.isDirectory()){ //文件夹
			File[] files = dirFile.listFiles();
			for (File f : files) {
				delDir(f);
			}
		}
		return dirFile.delete();
	 }


	/**
	 * 获取文件的后缀名
	 * @param appendDot 是否拼接.
	 * @return
	 */
	public static String getFileSuffix(String fullFileName, boolean appendDot){
		if(fullFileName == null || fullFileName.indexOf(".") < 0 || fullFileName.length() <= 1) return null;
		return (appendDot? "." : "") + fullFileName.substring(fullFileName.lastIndexOf(".") + 1);
	}


	public static String getFileName(String fullFileName){

		return fullFileName.substring(0, fullFileName.lastIndexOf("."));

	}

}
